//
//  XLLoginRegisterPresenter.m
//  industry
//
//  Created by xl on 2020/11/13.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLLoginRegisterPresenter.h"
#import "XLLoginRegisterPresenterProtocol.h"
#import "XLLoginRegisterViewProtocol.h"
#import "XLUserDefaults.h"
#import "XLAES128.h"
#import "XLNetworking.h"
#import "XLLoginRegisterInteractorProtocol.h"
#import "XLUserData.h"
#import "XLLoginModel.h"

@interface XLLoginRegisterPresenter ()<XLLoginRegisterPresenterProtocol>

@end
@implementation XLLoginRegisterPresenter

- (void)dealloc {
    XLLog(@"XLLoginRegisterPresenter dealloc");
}

#pragma mark - XLLoginRegisterPresenterProtocol
//获取AESkey执行对应操作
- (void)requestFetchAESKey:(XLFetchAESType)type
                     model:(XLLoginModel *)model {
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLFetchAESKeyUrl params:nil isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);

        NSString *aesKey = [dict objectForKey:@"data"];
        if (type == XLFetchAESTypeLogin) {//获取aes登录
            [strongSelf requestUserAccountLogin:model.account password:model.password isStaff:model.isStafff aesKey:aesKey isRecordPS:model.isRecordPS];
        } else if (type == XLFetchAESTypeFortgetPassword) {//获取aes设置忘记免密
            [strongSelf requestForgetPasswordFinish:model.phone password:model.password rePassword:model.rePassword isStaff:model.isStafff aesKey:aesKey];
        } else if (type == XLFetchAESTypeRegister) {//获取aes注册
            [strongSelf requestRegisterFinish:model.phone password:model.password rePassword:model.rePassword isStaff:model.isStafff aesKey:aesKey];
        }
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];

}

//用户账号登录
- (void)requestUserAccountLogin:(NSString *)account
                       password:(NSString *)password
                        isStaff:(BOOL)isStaff
                         aesKey:(NSString *)aesKey
                     isRecordPS:(BOOL)isRecordPS {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(account)) {
        [params setValue:account forKey:@"username"];
    }
    
    NSString *aesStr = [XLAES128 encryptStringWithString:password andKey:aesKey];
    if (!ISEmptyString(aesStr)) {
        [params setValue:aesStr forKey:@"password"];
    }
    [params setValue:@(isStaff) forKey:@"isStaff"];
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"登录中...");

    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLUserAccountLoginUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        //存储用户登录账号
        [XLUserDefaults saveLastLoginPhone:account];
        if (isRecordPS) {
            [XLUserDefaults saveLastLoginPassword:password];
        } else {
            [XLUserDefaults saveLastLoginPassword:nil];
        }
        
        [strongSelf handleLoginData:dict isStaff:isStaff];
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}

//手机验证码登录
- (void)requestSMSCodeLoginPhone:(NSString *)phone
                      verifyCode:(NSString *)verifyCode
                         isStaff:(BOOL)isStaff {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    if (!ISEmptyString(verifyCode)) {
        [params setValue:verifyCode forKey:@"verification"];
    }
    [params setValue:@(isStaff) forKey:@"isStaff"];
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    WEAKSELF
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"登录中...");
    [request requestWithMethod:XLHttpMedthTypeGET url:XLUserVerifyCodeLoginUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        
        //存储用户登录账号
        [XLUserDefaults saveLastLoginPhone:phone];
        
        [strongSelf handleLoginData:dict isStaff:isStaff];
        
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}

//校验图片码，以便获取短信校验码
- (void)requestCheckImageCode:(NSString *)imageCode
                        phone:(NSString *)phone
                   numberType:(NSInteger)numberType {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(imageCode)) {
        [params setValue:imageCode forKey:@"code"];
    }
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLCheckImageVerifyUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        
        //校验成功，获取短信校验码
        [strongSelf requestFetchSMSVerifyCode:phone numberType:numberType];
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreImageCodeCheck);
    }];
}

//获取校验码
- (void)requestFetchSMSVerifyCode:(NSString *)phone
                       numberType:(NSInteger)numberType {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    [params setValue:@(numberType) forKey:@"numberType"];//1忘记密码 2注册 3登录

    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"获取检验码中...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLFetchVerifyCodeUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        [XLToast showComonMessage:@"校验码发送成功"];
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreshVerificationCodeButtonState:YES);
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
         STRONGSELF
         XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreshVerificationCodeButtonState:NO);
    }];
}

//忘记密码或者注册下一步校验
- (void)requestCheckRegisterOrForgetNextPhone:(NSString *)phone
                                   numberType:(NSInteger)numberType
                                 verification:(NSString *)verification
                                      isStaff:(BOOL)isStaff {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    if (!ISEmptyString(verification)) {
        [params setValue:verification forKey:@"verification"];
    }
    [params setValue:@(numberType) forKey:@"numberType"];//1忘记密码 2注册 3登录
    XLHttpRequest *request = [[XLHttpRequest alloc] init];

    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"校验中...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLCheckVerifyCodeUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        if (numberType == 1) {//忘记密码
            XLSend(strongSelf.baseController.interactor, XLLoginRegisterInteractorProtocol, gotoForgetPSFinishVC:phone isStaff:isStaff);
        } else if (numberType == 2) {//注册
            XLSend(strongSelf.baseController.interactor, XLLoginRegisterInteractorProtocol, gotoRegisterFinishVC:phone isStaff:isStaff);
        }
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}
 
//忘记密码完成
- (void)requestForgetPasswordFinish:(NSString *)phone
                           password:(NSString *)password
                         rePassword:(NSString *)rePassword
                            isStaff:(BOOL)isStaff
                             aesKey:(NSString *)aesKey {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    NSString *passwordStr = [XLAES128 encryptStringWithString:password andKey:aesKey];
    if (!ISEmptyString(passwordStr)) {
        [params setValue:passwordStr forKey:@"newPassword"];
        [params setValue:passwordStr forKey:@"reNewPassword"];
    }
    [params setValue:@(isStaff) forKey:@"isStaff"];
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"加载中...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypePOST url:XLForgetPSFinishUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);

        [XLToast showSuccessMessage:@"设置密码成功"];
        //获取第一个vc
        XLBaseViewController *vc = strongSelf.baseController.navigationController.viewControllers.firstObject;
        [strongSelf.baseController.navigationController popToViewController:vc animated:YES];
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}


//注册最后一步设置密码
- (void)requestRegisterFinish:(NSString *)phone
                     password:(NSString *)password
                   rePassword:(NSString *)rePassword
                      isStaff:(BOOL)isStaff
                       aesKey:(NSString *)aesKey {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    NSString *passwordStr = [XLAES128 encryptStringWithString:password andKey:aesKey];
    if (!ISEmptyString(passwordStr)) {
        [params setValue:passwordStr forKey:@"password"];
        [params setValue:passwordStr forKey:@"rePassword"];
    }
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"加载中...");
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLRegisterPSFinishUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);

        [XLToast showSuccessMessage:@"注册成功"];
        
        //存储用户登录账号
        [XLUserDefaults saveLastLoginPhone:phone];
        [XLUserDefaults saveLastLoginPassword:password];

        //直接跳转首页
        [strongSelf handleLoginData:dict isStaff:NO];
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}

//是否显示员工登录按钮
- (void)requestShowStaffLoginStatus {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:XLAPPVERSION forKey:@"edition"];
    
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLShowStaffLoginButtonUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        id data = [dict objectForKey:@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSDictionary *temDic = (NSDictionary *)data;
            BOOL isChoice = [[temDic objectForKey:@"isChoice"]  boolValue];
            BOOL isVisible = [[temDic objectForKey:@"isVisible"] boolValue];
            XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreshStaffLoginSelectBtnStatus:isChoice isShow:isVisible);
        } else {
            XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreshStaffLoginSelectBtnStatus:YES isShow:NO);
        }

    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, refreshStaffLoginSelectBtnStatus:YES isShow:NO);
    }];
}

#pragma mark - Pirvate
- (void)handleLoginData:(NSDictionary *)dict
                isStaff:(BOOL)isStaff {
    [XLUserData sharedXLUserData].isHomeFirst = YES;
    [XLUserData sharedXLUserData].isMessageFirst = YES;
    [XLUserData sharedXLUserData].isApproveFirst = YES;
    [XLUserData sharedXLUserData].isUserCenterFirst = YES;
    id data = [dict objectForKey:@"data"];
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *temDic = (NSDictionary *)data;
        //获取token
        NSString *token = [temDic objectForKey:@"token"];
        if (!ISEmptyString(token)) {
            [XLUserDefaults saveLastAvailableToken:token];
        }
        [XLNetworking updateCustomHeaderDicWithToken:token];
        
        //存储用户信息
        XLUserInfo *model = [XLUserInfo mj_objectWithKeyValues:data];
        model.isStaff = isStaff;
        [[XLUserData sharedXLUserData] saveCurrentUserInfo:model];
        
        [XLNotif postNotificationName:XLNotificationUserLoginSuccess object:nil];
        //前往首页
        XLSend(self.baseController.interactor, XLLoginRegisterInteractorProtocol, gotoMainVC);
    }
}

//账号绑定
- (void)requestBindPhone:(NSString *)phone
                      verifyCode:(NSString *)verifyCode
                    openID:(NSString *)idcode
                         isStaff:(BOOL)isStaff
                      with:(XLLoginBindType)bindType{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(phone)) {
        [params setValue:phone forKey:@"phone"];
    }
    if (!ISEmptyString(verifyCode)) {
        [params setValue:verifyCode forKey:@"verification"];
    }
    [params setValue:@(isStaff) forKey:@"isStaff"];
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    
    NSString * url = @"";
    switch (bindType) {
        case XLLoginBindWeiXin:{
            url = XLWeiXinBiindUrl;
            [params setValue:idcode forKey:@"openId"];
        }
            break;
        case XLLoginBindApple:{
            url = XLAppleBiindUrl;
            [params setValue:idcode forKey:@"appleId"];
        }
            break;
        default:
            break;
    }
    
    WEAKSELF
    XLSend(self.baseController.cView, XLLoginRegisterViewProtocol, showLoadingAnimalWithTitle:@"绑定中...");
    [request requestWithMethod:XLHttpMedthTypeGET url:url params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
        
        //存储用户登录账号
        [XLUserDefaults saveLastLoginPhone:phone];
        
        [strongSelf handleLoginData:dict isStaff:isStaff];
        
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        XLSend(strongSelf.baseController.cView, XLLoginRegisterViewProtocol, hideLoadingAnimal);
    }];
}

@end
